package com.git.contractmanagement.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.git.contractmanagement.common.Result;
import com.git.contractmanagement.config.ZfbConfig;
import com.git.contractmanagement.entity.PayOrder;

import com.git.contractmanagement.service.PayOrderService;
import com.git.contractmanagement.service.ZfbPayService;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

@RestController
@CrossOrigin
@RequestMapping("pay")
public class ZfbController {
    @Autowired
    private ZfbPayService zfbPayService;
    @Autowired
    private PayOrderService payOrderService;
    @Autowired
    private ZfbConfig zfbConfig;

    /**
     * 提交订单，生成支付宝支付表单并跳转
     */
    @PostMapping("/zfb")
    public Result zfbPay(@RequestBody PayOrder payOrder, HttpServletResponse response) throws IOException {

        if (payOrder.getUserId() == null || payOrder.getAmount() == null) {
            return Result.error("userId 和 amount 不能为空");
        }
        // 生成唯一订单号
        String orderNo = new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date())
                + (new Random().nextInt(9000) + 1000);
        payOrder.setOrderNo(orderNo);
        payOrder.setCreateTime(new Date());
        payOrder.setStatus("PENDING");
        payOrder.setSubject("测试商品 - 支付宝支付");

        System.out.println("订单号：" + orderNo);
        System.out.println("payOrder 内容：" + payOrder);

        boolean saved = payOrderService.save(payOrder); // 或者 saveOrUpdate
        if (!saved) {
            return Result.error("保存订单失败");
        }

        String form = zfbPayService.createPayForm(payOrder);
        return Result.success(form);
    }

    /*
    退款业务，需要orderNo（订单号）和reason(原因)
    */
    @PostMapping("refund")
    public Result zfbRefund(String orderNo, String reason) {
        // 1. 查询订单
        System.out.println("11111111111111111111111111");
        PayOrder order = payOrderService.lambdaQuery()
                .eq(PayOrder::getOrderNo, orderNo)
                .one();
        // 2. 判断订单是否存在
        if (order == null) {
            return Result.error("订单不存在");
        }
        // 3. 判断订单是否已支付
        if (!"PAID".equals(order.getStatus())) {
            return Result.error("订单未支付，无法退款");
        }
        // 4. 调用退款服务
        try {
            System.out.println("222222222222222222");
            return zfbPayService.refund(order, reason);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("退款失败：" + e.getMessage());
        }
    }

    /**
     * 支付宝异步回调（支付成功后调用）
     */
    @PostMapping("/success")
    public String success(HttpServletRequest request) throws AlipayApiException, IOException {
        System.out.println("我到异步回调了");
        Map<String, String> params = new HashMap<>();
        request.getParameterMap().forEach((key, values) -> params.put(key, String.join(",", values)));
        // 1. 验签
        boolean verified = AlipaySignature.rsaCheckV1(
                params,
                zfbConfig.getAlipayPublicKey(),
                "UTF-8",
                "RSA2"
        );
        if (verified) {
            System.out.println("✅ 支付宝验签成功");


            String outTradeNo = params.get("out_trade_no"); // 商户订单号
            String tradeNo = params.get("trade_no");        // 支付宝交易号
            String totalAmount = params.get("total_amount");// 支付金额
            String buyerId = params.get("buyer_id");        // 支付宝买家id// 获取支付宝回调参数
            String passbackParams = params.get("passback_params");

            if (passbackParams != null) {
                // 需要 URL 解码
                passbackParams = URLDecoder.decode(passbackParams, StandardCharsets.UTF_8.name());

                // 例如你传的是 userId=12345，这里就能解析出来
                String[] kv = passbackParams.split("=");
                if (kv.length == 2 && "userId".equals(kv[0])) {
                    String userId = kv[1];
                    System.out.println(" 回调中的用户ID: " + userId);
                }
            }
            // 3. 更新支付记录
            PayOrder order = payOrderService.lambdaQuery()
                    .eq(PayOrder::getOrderNo, outTradeNo)  // outTradeNo 必须等于数据库的 orderNo
                    .one();

            if (order != null) {
                order.setTradeNo(tradeNo);
                order.setStatus("PAID");
                payOrderService.updateById(order);
            } else {
                // 不要随便插入新记录，记录日志即可
                System.out.println("订单不存在：" + outTradeNo);
            }

            String status = payOrderService.paySuccess(tradeNo);

            // 4. 返回支付宝要求的 success
            return status;

        } else {
            System.out.println(" 验签失败");
            return "failure";
        }
    }
}
